package com.yanggu.scala.chapater11.exercise

import scala.collection.mutable

object Exercise03 {

  def main(args: Array[String]): Unit = {
    //统计字符出现的个数
    //这里需要注意fold和foldLeft之间的区别。在泛型的使用上fold必须使用Any
    //这里使用mutable的Map效率更高
    val sentence = "AAAAAAAAAABBBBBBBBCCCCCDDDDDDD"

    def charCount(map: mutable.Map[Char, Int], c: Char) = {
      map += (c -> (map.getOrElse(c, 0) + 1))
    }

    val charToIntMap = mutable.Map[Char, Int]()
    println(sentence.foldLeft(charToIntMap)(charCount))
    println(sentence.foldLeft(charToIntMap)((map, c) => map += (c -> (map.getOrElse(c, 0) + 1))))
    println(charToIntMap)
  }

}
